package com.amigo.online.provider.adv.aspect;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.amigo.online.provider.adv.entity.RequestLog;
import com.amigo.online.provider.adv.interceptor.LoggerInterceptor;
import com.amigo.online.provider.adv.util.LoggerUtil;

@Aspect
@Order(-99)//多个Aspect 顺序越小越先执行！
@Component
public class LogAopAction {

    private static final Logger logger = LoggerFactory.getLogger(LogAopAction.class);

    /**
     * @throws
     * @Title: pointCutMethod
     * @Description: (定义Controller拦截规则)
     * @param:
     * @return: void
     */
    @Pointcut("execution(* com.amigo.online.provider.adv.controller..*(..))")
    private void pointCutMethod() {
    }

    /**
     * 记录操作日志
     */
    @Before("pointCutMethod()")  // 使用上面定义的切入点
    public void recordLog(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        RequestLog requestLog = (RequestLog) request.getAttribute(LoggerInterceptor.LOGGER_MODEL);
        Object[] args = joinPoint.getArgs();
        Map<String, String> paramMap = new HashMap<>();
        for (Object obj : args) {
            paramMap.put(obj.getClass().getSimpleName(), obj.toString());
        }
        requestLog.setParamMap(paramMap);
        logger.info("-----------存储用户请求调用的方法信息----");
    }

    @Deprecated
    private Map<String, String> getLogMark(JoinPoint joinPoint) throws ClassNotFoundException {
        Map<String, String> map = new HashMap<>();
        String methodName = joinPoint.getSignature().getName();
        String targetName = joinPoint.getTarget().getClass().getName();
        Class<?> targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
                map.put(LoggerUtil.LOG_TARGET_TYPE, logAnnotation.targetType());
                map.put(LoggerUtil.LOG_ACTION, logAnnotation.action());
                map.put(LoggerUtil.LOG_REMARK, logAnnotation.remark());
            }
        }
        return map;
    }
}
